package com.yiya.ms.action;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.OrderDetail;
import com.yiya.bean.OrderInfo;
import com.yiya.bean.SysUser;
import com.yiya.model.OrderInfoCplex;
import com.yiya.model.OrderInfoCplexModel;
import com.yiya.service.OrderInfoService;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/order_info")
public class OrderInfoAction extends BaseAction {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(OrderInfoAction.class);

	@Autowired
	private OrderInfoService orderInfoService;
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }
		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        
		});
	}
	
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request) {
		Map<String, Object> context = getRootMap();
		return forword("order_info/order_info", context);
	}
	
	@RequestMapping("/dataList")
	public void datalist(OrderInfoCplexModel model, HttpServletResponse response)
			throws Exception {
		List<OrderInfoCplex> list = orderInfoService.queryByList(model);
		int count = orderInfoService.queryByCount(model);
		// 设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("rows", list);
		jsonMap.put("total", count);
		HtmlUtil.writerJson(response, jsonMap);
	}
	
	@RequestMapping("/save")
	public void save(OrderInfo bean,HttpServletRequest request,HttpServletResponse response){
		Date nowTime = new Date();
		SysUser user = SessionUtils.getUser(request);
		List<OrderDetail> orderDetails = getReqOrderDetail(request);
		bean.setOrderDetails(orderDetails);
		if(bean.getId() == null){
			bean.setCreateTime(nowTime);
			bean.setCreateBy(user.getId());
			orderInfoService.add(bean);
		}else{
			bean.setUpdateBy(user.getId());
			bean.setUpdateTime(nowTime);
			orderInfoService.Update(bean);
		}
		sendSuccessMessage(response, "保存成功");
	}
	
	/**
	 * 获取请求的订单子项
	 * @param request
	 * @return
	 */
	public List<OrderDetail> getReqOrderDetail(HttpServletRequest request){
		SysUser user = SessionUtils.getUser(request);
		Date nowTime = new Date();
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		String[] orderDetailId = request.getParameterValues("orderDetailId");
		String[] product = request.getParameterValues("product");
		String[] color = request.getParameterValues("color");
		String[] quantity = request.getParameterValues("quantity");
		String[] deleteFlag = request.getParameterValues("deleteFlag");
		if(orderDetailId  == null || orderDetailId.length < 1){
			return null;
		}
		for (int i = 0; i < orderDetailId.length; i++) {
			if(StringUtils.isNotBlank(product[i])){
				OrderDetail orderDetail = new OrderDetail();
				if(StringUtils.isNotBlank(orderDetailId[i]) && NumberUtils.isNumber(orderDetailId[i])){
					orderDetail.setId(NumberUtils.toInt(orderDetailId[i]));
					orderDetail.setUpdateBy(user.getId());
					orderDetail.setUpdateTime(nowTime);
				}
				orderDetail.setProduct(product[i]);
				orderDetail.setColor(color[i]);
				orderDetail.setQuantity(quantity[i]==null||"".equals(quantity[i])?0:Integer.valueOf(quantity[i]));
				orderDetail.setDelFlag(deleteFlag[i]==null||"".equals(deleteFlag[i])?0:Integer.valueOf(deleteFlag[i]));
				orderDetail.setCreateBy(user.getId());
				orderDetail.setCreateTime(nowTime);
				orderDetails.add(orderDetail);
			}
		}
		return orderDetails;
	}
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response){
		Map<String,Object>  context = getRootMap();
		OrderInfo bean = orderInfoService.queryById(id);
		if(bean  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		List<OrderDetail> orderDetails = orderInfoService.queryByOrderId(id);
		bean.setOrderDetails(orderDetails);
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		orderInfoService.delete(id,user);
		sendSuccessMessage(response, "删除成功");
	}
	
	@RequestMapping("/queryAllOrderInfos")
	public void queryAllOrderInfos(OrderInfoCplexModel model,
			HttpServletResponse response) throws Exception {
		List<OrderInfoCplex> orderInfos = orderInfoService.queryAllByList(model);
		HtmlUtil.writerJson(response, orderInfos);
	}
}
